package cn.luow.mail.interceptor;


import cn.luow.mail.config.MailConfig;
import cn.luow.mail.pojo.MagicLogs;
import cn.luow.mail.service.IMailService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.core.service.MagicResourceService;

import javax.annotation.Resource;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用作记录接口日志
 */
@Component
@Slf4j
public class MagicApiLogInterceptor implements RequestInterceptor {

    @Resource
    private IMailService mailService;

    @Resource
    private MagicResourceService magicResourceService;

    @Resource
    private MailConfig mailConfig;

    @Value("${magic-api.web}")
    private String web;

    private ExpiringMap<MagicLogs, java.util.Date> cache;
    @Override
    public void afterCompletion(RequestEntity requestEntity, Object returnValue, Throwable throwable) {
        String logMail = requestEntity.getApiInfo().getOptionValue(mailConfig.getKeyword());
        if("true".equals(logMail)){
            MagicLogs logs = new MagicLogs();
            logs.setPath(magicResourceService.getGroupPath(requestEntity.getApiInfo().getGroupId())+"/"+requestEntity.getApiInfo().getPath());
            logs.setCreateTime(new Date(System.currentTimeMillis()));
            logs.setDelFlag(0L);
            logs.setRequestMethod(requestEntity.getApiInfo().getMethod());
            logs.setRequestParams(JSON.toJSONString(requestEntity.getParameters()));
            logs.setType(0L);
            logs.setResponse(JSON.toJSONString(returnValue));
            logs.setDescription(requestEntity.getApiInfo().getName());
            if(!requestEntity.getApiInfo().getMethod().equalsIgnoreCase("GET"))
            {
                logs.setRequestBody(JSON.toJSONString(requestEntity.getRequestBody()));
            }
            if(throwable!=null)
            {
                logs.setType(1L);
                logs.setErrorMsg(throwable.getMessage());
                logs.setFullError(getStackTrace(throwable));
                if(cache==null){
                    cache = ExpiringMap.builder()
                            .expiration(mailConfig.getDuration(), TimeUnit.MINUTES)
                            .expirationPolicy(ExpirationPolicy.CREATED)
                            .build();
                }
                java.util.Date date = cache.get(logs);
                if(date==null){//未存在或已过期
                    cache.put(logs,new java.util.Date());
                    Map<String ,Object> map = (Map<String ,Object> )JSON.parse(JSON.toJSONString(logs));
                    map.put("web",web);
                    mailService.send("接口异常提醒",mailConfig.getLogFtl(),map);
                }else{
                    log.info("【{}】接口{}分钟内已发送过报错邮件",logs.getPath(),mailConfig.getDuration());
                }
            }
        }

    }


    public String getStackTrace(Throwable throwable){
        StringWriter stringWriter=new StringWriter();
        try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
            throwable.printStackTrace(printWriter);
            return stringWriter.toString();
        }
    }
}
